import 'package:find_friend/common/common_widget.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/mine/mine_preview_page.dart';
import 'package:find_friend/pages/mine/model/followmodel.dart';
import 'package:find_friend/pages/search/hotmodel.dart';
import 'package:find_friend/pages/search/search_res.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SearchPage extends StatefulWidget {
  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {

  FocusNode focusNode = FocusNode();
  TextEditingController _controller = TextEditingController();
  static const String Key_history_keword = "Key_history_keword";
  List<String> localSearch = [];
  List<String> hotKeyword = [];
  List<FollowModel> hotUsers = [];
  List<String> icons = ["h4.png", "h3.png", "h2.png", "h1.png"];
  bool issearch = false;
  SearchResList searchList = SearchResList();

  @override
  void initState() {
    super.initState();

    _cacheSearch();
    _request();
  }

  _search(String val) {
    _cacheSearch(val);
  }

  _cacheSearch([String val]) {
    SharedPreferences.getInstance().then((value) {
      List<String> list = value.getStringList(Key_history_keword) ?? [];
      if(!list.contains(val) && val != null && val.trim() != "") {
        list.add(val);
      }
      setState(() {
        localSearch = list;
      });
      value.setStringList(Key_history_keword, list);
    });
    if(val != null){
      setState(() {
        issearch = true;
      });
      searchList.search(val);
    }
  }

  void _request() {
    Networktool.request(API.hotsearch, params: {"searchflag": "hot"}, method: NETWORKHTTPMethod.GET, success: (data){
      if(data["data"] != null) {
        HotSearchResponse hot = HotSearchResponse.fromJson(data);
        if(hot.data?.hot != null){
          hotKeyword = hot.data?.hot ?? [];
        }
        if(hot.data?.user != null) {
          hotUsers = hot.data?.user ?? [];
        }
        if(mounted) {
          setState(() {
          });
        }
      }
    });
  }

  // 标题
  Widget _createSearchTitle(String title, String icon) {
    return Padding(
      padding: const EdgeInsets.only(left:15.0),
      child: Row(
        children: [
          Image.asset("assets/$icon"),
          SizedBox(width: 3.5,),
          Text(title, style: instanceTextStyle(15, APP_font_black, fontWeight: FontWeight.w600))
        ],
      ),
    );
  }

  // 历史搜索
  Widget _createLocal(String title) {
    return InkWell(
      onTap: (){
        _controller.text = title;
        _cacheSearch(title);
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(width: 0.5, color: APP_divider_color),
          borderRadius: BorderRadius.circular(5)
        ),
        child: Text(title, style: instanceTextStyle(14, APP_font_grey),)
      ),
    );
  }

  // 热门用户
  Widget _createHotuser(FollowModel model) {

    final size = MediaQuery.of(context).size;
    int index = hotUsers.indexOf(model) % icons.length;
    return InkWell(
      onTap: (){
        push(context, MinePreviewPage(mobile: model.mobile));
      },
      child: Container(
        height: 40,
        width: (size.width - 40 - 30) / 2.0,
        child: Stack(
          children: [
            Positioned(
              top: 10,
              left: 0,
              child: Row(
                children: [
                  CustomCircleAvatar(size: 28, url: model.avatar,),
                  Text(model.followRemark ?? "", style: instanceTextStyle(14, APP_font_black),)
                ],
              ),
            ),
            Positioned(
              top: 0,
              left: 14,
              child: Image.asset("assets/${icons[index]}", height: 19, fit: BoxFit.scaleDown,)
            ),
          ],
        ),
      ),
    );
  }

  Widget _createHostSearch(String tag) {

    final size = MediaQuery.of(context).size;
    int index = hotKeyword.indexOf(tag);
    return InkWell(
      onTap: (){
        setState(() {
          issearch = true;
        });
        _controller.text = tag;
        _cacheSearch(tag);
      },
      child: Container(
        width: (size.width - 26 * 2 - 30) / 2.0,
        child: Text.rich(
          TextSpan(
            children: [
              TextSpan(text: "${index + 1}", style: instanceTextStyle(14, index < 4 ? APP_main_color : APP_font_deep_grey, fontWeight: FontWeight.w600)),
              WidgetSpan(child: SizedBox(width: 5,)),
              TextSpan(text: tag, style: instanceTextStyle(14, APP_font_black)),
            ]
          )
        ),
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      body: SafeArea(
        child: Stack(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  margin: const EdgeInsets.all(10),
                  height: 40.h,
                  child: Row(
                    children: [
                      Flexible(
                        child: TextField(
                          onSubmitted: _search,
                          controller: _controller,
                          decoration:InputDecoration(
                                hintText: "想找啥~",
                                counterText: "",
                                focusedBorder: OutlineInputBorder(
                                borderRadius: const BorderRadius.all(Radius.circular(25)),
                                borderSide: const BorderSide(width: 1.5, color: Colors.black),
                              ),
                              hintStyle: instanceTextStyle(14, APP_font_deep_grey),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: const BorderRadius.all(Radius.circular(25)),
                                borderSide: const BorderSide(width: 1.5, color: Colors.black),
                              ),
                              border: OutlineInputBorder(
                                borderRadius: const BorderRadius.all(Radius.circular(25)),
                                borderSide: const BorderSide(width: 1.5, color: Colors.black),
                              ),
                              contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                              prefixIcon: Image.asset("assets/sousuo.png", color: APP_font_grey,),
                          ),
                          focusNode: focusNode,
                        ),
                      ),

                      InkWell(
                        onTap: () => Navigator.pop(context),
                        child: Container(
                          height: 40.h,
                          alignment: Alignment.center,
                          padding: const EdgeInsets.only(left: 10.0),
                          child: Text("取消", style: instanceTextStyle(14, APP_font_black),),
                        ),
                      )
                    ],
                  ),
                ),

                Container(
                  padding: const EdgeInsets.only(left:15.0,),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Image.asset("assets/lishi.png"),
                      SizedBox(width: 3.5,),
                      Expanded(child: Text("最近搜索", style: instanceTextStyle(15, APP_font_black, fontWeight: FontWeight.w600),)),
                      IconButton(
                        icon: Image.asset("assets/lajit.png", color: APP_font_deep_grey,),
                        onPressed: (){
                          SharedPreferences.getInstance().then((value) {
                            value.remove(Key_history_keword);
                            _cacheSearch();
                          });
                        },
                      )
                      
                    ],
                  ),
                ),

                // 历史搜搜
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20),
                  child: Wrap(
                    spacing: 10,
                    runSpacing: 5,
                    children: localSearch.map((e) => _createLocal(e)).toList(),
                  ),
                ),
                SizedBox(height: 25,),
                // 热门用户
                _createSearchTitle("热门用户", "yhu.png"),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                  child: Wrap(
                    spacing: 10,
                    runSpacing: 5,
                    children: hotUsers.map((e) => _createHotuser(e)).toList(),
                  ),
                ),
                SizedBox(height: 10,),
                // 热门搜索
                _createSearchTitle("热门搜索", "ssou.png"),
                SizedBox(height: 10,),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 26),
                  child: Wrap(
                      spacing: 10,
                      runSpacing: 5,
                      children: hotKeyword.map((e) => _createHostSearch(e)).toList(),
                    ),
                ),
              ],
            ),

            Positioned.fill(
              top: 40.h + 10,
              child: Offstage(
                offstage: !issearch,
                child: searchList,
              )
            )
          ],
        ),
      ),
    );
  }
}